import { AnyColumn } from "element-plus/es/components/table-v2/src/common.mjs";

let popupList: any = []  // 存储popup实例
const popupManager = {
    // 创建popup
    createPopup(map: any, id: string, coordinates: any, content: string) {
        const offset = {
            top: [0, 0],    // 偏移量，设置Popup顶部的偏移
            bottom: [0, -10],  // 设置Popup底部的偏移
            left: [0, 0],    // 设置Popup左侧的偏移
            right: [0, 0],   // 设置Popup右侧的偏移
        };

        let popup = new mapboxgl.Popup({
            closeButton: false,  // 不显示关闭按钮
            closeOnClick: false, // 点击地图时不关闭 Popup
            offset: offset // 设置偏移量
        })
            .setLngLat(coordinates)
            .setHTML(content)
            .addTo(map)

        popupList.push({ id, popup });
    },
    // 根据id获取popup
    getPopupById(id: string) {
        if (popupList.length === 0) {
            return null
        } else {
            const index = popupList.findIndex(m => m.id === id)
            if (index === -1) {
                return null
            }

            return popupList[index].popup
        }

    },
    // 根据id更新popup内容
    updatePopup(popup: any, newContent: string) {
        if (popup) {
            popup.setHTML(newContent)
        }
    },
    // 根据id更新popup位置
    updatePopupPositition(id: string, coordinates: [number, number]) {
        let popup = this.getPopupById(id)
        if (popup) {
            popup.setLngLat(coordinates)
        }

    },
    // 打开指定的popup
    openPopup(map: any, id: string) {
        const popup = this.getPopupById(id)
        if (popup) {
            popup.addTo(map)
        }
    },
    // 关闭并移除指定的popup
    closePopup(id: string) {
        const index = popupList.findIndex((item: { id: string; }) => item.id === id)
        if (index !== -1) {
            popupList[index].popup.remove()
            popupList.splice(index, 1)
        }
    },
    // 关闭并移除所有popup
    closeAllPopup() {
        popupList.forEach((item: { popup: any; }) => {
            item.popup.remove()
        })
        popupList = []
    },
    // 获取所有popup列表
    getAllPopup() {
        return popupList.map((item: { popup: any; }) => item.popup)
    }

}

export { popupManager }